package com.vhall.component.service.redpacket.service.impl;

/**
 * @author xuyongzheng
 * @since 2021/3/20 22:29
 **/

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.vhall.component.entity.rebroadcast.RedPacketSettingEntity;
import com.vhall.component.plugin.common.constant.HttpConstant;
import com.vhall.component.plugin.common.constant.PaasCommonConstant;
import com.vhall.component.service.redpacket.service.RedPacketSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

@Slf4j
@Service
public class InnerPayService {
    @Autowired
    private RedPacketSettingService redPacketSettingService;

    /**
     * 检查支付服务是否 支付成功
     *
     * @param appId     app id
     * @param accountId 3rd user id
     * @param roomId    source id
     * @param amount    amount
     * @return true| false
     */
    public Boolean payOrReturnRedPacketCallback(String appId, Integer accountId, String roomId,
                                                BigDecimal amount, String event) {
        event = StringUtils.isBlank(event) ? "SEND_RED_PACKET" : event;
        RedPacketSettingEntity setting = redPacketSettingService.getRowByAppId(appId);
        if (setting == null) {
            return true;
        }
        if (StringUtils.isBlank(setting.getPayCallbackUrl())) {
            return true;
        }
        if (!(Pattern.matches("^(?i)http.*", setting.getPayCallbackUrl()))) {
            return false;
        }
        try {
            HashMap<String, Object> map = Maps.newHashMap();
            map.put(PaasCommonConstant.THIRD_PARTY_USER_ID_KEY, accountId);
            map.put("amount", amount);
            map.put("source_id", roomId);
            map.put("event", event);
            String signature = makeSignature(map, setting.getPrivateKey());
            map.put("signature", signature);
            String response = HttpUtil.post(setting.getPayCallbackUrl(), map, 3000);

            JSONObject result = JSON.parseObject(response);
            if (result.getInteger(HttpConstant.CODE) != HttpConstant.SUCCESS_CODE) {
                log.warn("调用支付回调地址失败，请求参数:{}，返回结果:{}", map, result.toJSONString());
                // throw new BusinessException(RspCode.PAY_FAIL);
            }
            return true;
        } catch (Exception ex) {
            log.error("调用支付回调地址失败:", ex);
        }
        return false;
    }

    /**
     * 领取到红包获取回调
     */
    public Boolean getRedPacketCallback(String appId, Integer thirdPartyUserId, long getPacketRecordId,
                                        BigDecimal amount) {
        RedPacketSettingEntity setting = redPacketSettingService.getRowByAppId(appId);
        if (setting == null) {
            return true;
        }
        if (StringUtils.isBlank(setting.getGetRedPacketCallbackUrl())) {
            return true;
        }
        if (!(Pattern.matches("^(?i)http.*", setting.getGetRedPacketCallbackUrl()))) {
            return false;
        }
        try {
            HashMap<String, Object> map = Maps.newHashMap();
            map.put(PaasCommonConstant.THIRD_PARTY_USER_ID_KEY, thirdPartyUserId);
            map.put("amount", amount);
            map.put("source_id", getPacketRecordId);
            map.put("event", "GET_RED_PACKET");
            String signature = makeSignature(map, setting.getPrivateKey());
            map.put("signature", signature);
            String response = HttpUtil.post(setting.getGetRedPacketCallbackUrl(), map, 3000);
            JSONObject result = JSON.parseObject(response);
            if (result.getInteger(HttpConstant.CODE) != HttpConstant.SUCCESS_CODE) {
                log.warn("调用领取红包后的回调地址失败，请求参数:{}，返回结果:{}", map, result.toJSONString());
                // throw new BusinessException(RspCode.PAY_FAIL);
            }
            return true;
        } catch (Exception ex) {
            log.error("调用领取红包后的回调地址失败:", ex);
        }
        return false;
    }


    public String makeSignature(Map<String, Object> map, String privateKey) {
        // map排序
        Set<String> set = map.keySet();
        Object[] arr = set.toArray();
        Arrays.sort(arr);
        StringBuilder stringBuilder = new StringBuilder("");
        String s = DigestUtils.md5DigestAsHex(privateKey.getBytes());
        for (Object key : arr) {
            stringBuilder.append(key).append("|").append(s).append("|").append(map.get(key));
        }
        return DigestUtils.md5DigestAsHex(stringBuilder.toString().getBytes());
    }
}
